#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace My_Log;

const in_port_t defport = 8080;
const std::string defip = "127.0.0.1";

class TcpServer
{
public:
    TcpServer(in_port_t port = defport, std::string ip = defip)
        : _listensockfd(-1), _isrunning(false), _addr(port)
    {
    }
    void InitServer()
    {
        // 创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket err: " << strerror(errno);
            exit(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success";

        // bind套接字
        int n = bind(_listensockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            exit(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";

        // 监听套接字
        n = listen(_listensockfd, 4);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen: " << strerror(errno);
            exit(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success";
    }
    void Start()
    {
        _isrunning = true;

        while (true)
        {
            struct sockaddr_in cliaddr;
            socklen_t len = sizeof(cliaddr);

            int sockfd = accept(_listensockfd, CONV(&cliaddr), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept: fail";
            }

            LOG(LogLevel::INFO) << "accept success, sockfd is : " << sockfd;

        }
    }
    ~TcpServer()
    {
    }

private:
    int _listensockfd;
    InetAddr _addr;
    bool _isrunning;
};